<template>
  <view class="container" @touchend="offCheckbox" @touchmove="handlerTouchMove">
    <view class="main">
      <view
        class="card-item"
        v-for="(clock, index) in clocks"
        :key="clock.taskName"
      >
        <span
          :style="[checkboxStyle(index)]"
          @click.stop="select(index)"
          @touchend.stop
          class="checkbox"
        ></span>
        <schedule-card
          @nav-to="navTo"
          @trigger.stop="trigger"
          @touch-continue="touchContinue"
          :clock-item="clock"
          :index="index"
          class="schedule-card"
          :style="[scheduleCardStyle]"
        />
      </view>
      <schedule-card @add-clock="addClock" />
    </view>
    <view class="delete" v-show="isDelete" @touchend.stop @click.stop="deleteTask">
      <button type="warn">删除</button>
    </view>
    <view class="create" v-show="isCreate">
      <clock-profile :visiable.sync="isCreate" @submit="createSubmit" />
    </view>
  </view>
</template>

<script>
import ScheduleCard from "../../../components/ScheduleCard";
import { changeClockState, deleteClockItem, deleteManyClockItem, getClocks } from "../../../api/clock";
import { subscribeMessage } from '../../../utils/wx';
import ClockProfile from "./create";
export default {
  name: "schedule",
  created() {
    getClocks().then((res) => {
      const { success, clocks } = res.data;
      if (success) {
        clocks.forEach((clock) => {
          const { tags, target_timestamp, now_timestamp, playing, id } = clock;
          const task = {
            taskName: clock.name,
            tags,
            target_timestamp,
            now_timestamp,
            playing,
            id,
          };
          // 初始化正在运行的clock，放入playingStack中
          if (playing) {
            this.playingStack.push(task);
          }

          this.addTask(task);
        });
      }
    });
    this.timer = setInterval(() => {
      const deleteStack = [];
      this.playingStack.forEach(clock => {
        clock.now_timestamp += 1000;
        if (clock.now_timestamp >= clock.target_timestamp) {
          clock.now_timestamp = 0;
          clock.playing = false;
          clock.isAward = true;
          deleteStack.push(clock);
        }
      });
      // 时间结束后出栈
      deleteStack.forEach(deleteClock => {
        const index = this.playingStack.findIndex(val => {
          if (val.taskName === deleteClock.taskName) {
            return true;
          }
        });
        if (index !== -1) {
          this.playingStack.splice(index, 1);
        }
      })
      
    }, 1000);
  },
  destroyed() {
    clearInterval(this.timer);
  },
  data() {
    return {
      timer: 0,
      playingStack: [],
      isDelete: false,
      // 防止第一次触发touchContinue后的touchend将左边checkbox关掉
      isUpCheckbox: false,
      // 移动后不让左边checkbox消失
      isTouchMove: false,
      displayCheckbox: false,
      checkbox: [],
      clocks: [],
      isCreate: false,
    };
  },
  computed: {
    checkboxStyle() {
      return (index) => {
        if (this.checkbox[index].active) {
          return {
            background: "green",
          };
        } else {
          return {};
        }
      };
    },
    scheduleCardStyle() {
      if (this.displayCheckbox) {
        return {
          marginLeft: '78rpx',
        }
      } else {
        return {
          marginLeft: 0,
        }
      }
    }
  },
  methods: {
    handlerTouchMove() {
      this.isTouchMove = true;
    },
    addTask(item) {
      this.clocks.push(item);
      this.checkbox.push({
        active: false,
      });
    },
    async deleteTask() {
      this.isDelete = false;
      this.displayCheckbox = false;
      const clocks = [];
      const checkbox = [];
      const deleteStack = [];
      this.checkbox.forEach((item, index) => {
        if (item.active === false) {
          clocks.push(this.clocks[index]);
          checkbox.push(item);
        } else {
          deleteStack.push(this.clocks[index]);
          
        }
      });
      deleteStack.forEach(clock => {
        const sit = this.playingStack.findIndex((item) => {
            if (item.taskName === clock.taskName) {
              return true;
            }
          });
          // 删除后需要将运行栈中的删掉
          if (sit !== -1) {
            this.playingStack.splice(sit, 1);
          }
      })
      if (deleteStack.length === 1) {
        await deleteClockItem(deleteStack[0].id);
      } else if (deleteStack.length > 1) {
        console.log(deleteStack);
        await deleteManyClockItem(deleteStack.reduce((sum, item) => {
          sum.push(item.id);
          return sum;
        }, []));
      }
      this.clocks = clocks;
      this.checkbox = checkbox;
    },
    async trigger(config) {
      const { index, id } = config; 
      if (!this.clocks[index].playing) {
        try {
          const submessageReq = await subscribeMessage();
          console.log(submessageReq);
        } catch(err) {
          // 如果报错表示没登陆
          await this.$store.dispatch('login')
            .then(async () => {
              const submessageReq = await subscribeMessage();
            })
        }
      } 
      await changeClockState(id, !this.clocks[index].playing? 'start': 'stop');

      this.clocks[index].playing = !this.clocks[index].playing;
      if (this.clocks[index].playing) {
        this.playingStack.push(this.clocks[index]);
      } else {
        const sit = this.playingStack.findIndex((item) => {
          if (item.taskName === this.clocks[index].taskName) {
            return true;
          }
        });
        if (sit !== -1) {
          this.playingStack.splice(sit, 1);
        }
      }
    },
    async addClock() {
      this.isCreate = true;
    },
    navTo(item) {
      console.log(item);
    },
    touchContinue() {
      console.log("touch-continue");
      this.checkbox.forEach((item) => {
        item.active = false;
      });
      this.isUpCheckbox = true;
      this.displayCheckbox = true;
    },
    offCheckbox() {
      if (!this.isTouchMove && !this.isUpCheckbox) {
        this.displayCheckbox = false;
        // 关闭侧边checkbox后要将刚才选择的置false
        this.checkbox.forEach((item) => {
          item.active = false;
        });
        this.isDelete = false;
      }
      this.isTouchMove = false;
      this.isUpCheckbox = false;
    },
    select(index) {
      this.checkbox[index].active = !this.checkbox[index].active;
      // 只要存在一个active为true就可以删除
      this.isDelete = false;
      for (let v of this.checkbox) {
        if (v.active === true) {
          this.isDelete = true;
          break;
        }
      }
    },
    createSubmit(clock) {
      const {
        name: taskName,
        tags,
        target: target_timestamp,
        now_timestamp = 0,
        playing = false,
        id,
      } = clock;
      const item = {
        taskName,
        tags,
        target_timestamp: target_timestamp * 1000 * 60, // 换算成毫秒
        now_timestamp,
        playing,
        id
      };
      this.addTask(item);
    },
  },
  components: {
    ScheduleCard,
    ClockProfile,
  },
};
</script>

<style scoped>
.create {
  position: absolute;
  width: 100%;
  height: 100vh;
  z-index: 101;
}
.container {
  width: 90%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.container .main {
  width: 100%;
  height: auto;
  display: flex;
  flex-direction: column;
}
.container .main > .card-item {
  display: flex;
  align-items: center;
  position: relative;
}
.checkbox {
  border-radius: 50%;
  height: 32rpx;
  width: 32rpx;
  border: green 2px solid;
  flex-shrink: 0;
  margin-right: 48rpx;
  position: absolute;
  z-index: 1;
}
.schedule-card {
  z-index: 2;
  transition: margin .1s;
}
.delete {
  position: fixed;
  bottom: 200rpx;
  width: 256rpx;
  z-index: 100;
}
</style>